package odgs.app.server;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JTextArea;

import odgs.Contents;
import odgs.ContentsFile;
import odgs.Directory;
import odgs.ExplorerNode;
import odgs.app.common.LogViewUI;
import odgs.listener.ServerManagerListener;
import odgs.manager.ServerManager;

public class ServerManagerLogViewController implements ServerManagerListener{

	private LogViewUI ui;
	private ServerManager manager;
	private JTextArea viewer;

	public ServerManagerLogViewController(LogViewUI ui) {
		this.ui = ui;
		ui.scroller.setAutoscrolls(true);
		viewer = ui.view;
		viewer.setLineWrap(true);
		viewer.setEditable(false);
	}

	public void setServerManager(ServerManager manager) {
		this.manager = manager;
		manager.addServerManagerListener(this);
		log("Log Start!");
	}

	public void loginedNode(String id)
	{
		viewerlog("login \"" + id + "\"");
	}
	
	private String getTime() {
		SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
		return format.format(new Date());
	}

	public void addedContents(Contents contents) 
	{
		viewerlog("Added File " + contents.getOwner() + "'s \"" + contents.getPath() + contents.toString() + "\"");
	}
	
	public void addedDirectory(Directory directory) 
	{
		viewerlog("Added Directory " + directory.getOwner() + "'s \"" + directory.getPath() + directory.toString() + "\"");
	}
	
	public void error(int error)
	{
		viewerlog("Error Code = " + error);
	}

	public void joinedNode(String id)
	{
		viewerlog("join \"" + id + "\"");
	}

	public void removeContents(Contents contents)
	{
		viewerlog("Removed File " + contents.getOwner() + "'s \"" + contents.getPath() + contents.toString() + "\"");
	}
	
	private void viewerlog(String log) {
		log(" Logic Log : " + log);
	}

	public void removeDirectory(Directory directory) 
	{
		viewerlog("Removed Directory " + directory.getOwner() + "'s  \"" + directory.getPath() + directory.toString() + "\"");
	}

	public void logout(String id)
	{
		viewerlog("logout \"" + id + "\"");
	}
	
	public void updatedExplorerNode(String mode, ExplorerNode node, String dest)
	{
		if("move".equals(mode))
			viewerlog("changed moved " + node.getOwner() + "'s \"" + node.getPath() + node + "\" -> \"" + dest + node + "\"");
		else
			viewerlog("changed renamed " + node.getOwner() + "'s \"" + node.getPath() + node + "\" -> \"" + dest + "\"");
	}

	public void log(String log) {
		viewer.append("  (" + getTime() + ") " + log + "\n\r");
		viewer.setCaretPosition(viewer.getDocument().getLength());
	}

	public void freeStorage(ContentsFile file){}
	public void useStorage(ContentsFile file){}
	public void serverOpened(int port){}
}
